package core.pojos;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Admin
 */
public class MergedList {

    private Map<String, ItemInfo> map = new HashMap<String, ItemInfo>();

    public MergedList() {
    }

    public void merge(List<ItemInfo> list) {
        for (ItemInfo item : list) {
            String key = generateKey(item);
            if (!map.containsKey(key)) {
                map.put(key, item);
            } else {
                map.get(key).addItem(item);
            }
        }
    }

    public List<ItemInfo> getList() {
        ArrayList<ItemInfo> list = new ArrayList<ItemInfo>();
        for (ItemInfo item : map.values()) {
            if (item.getItems().isEmpty()) {
                list.add(item);
            } else {
                ItemInfo temp = new ItemInfo(item.getName(),
                        item.isDir(), item.getFileExtension());
                temp.addItem(item);
                temp.getItems().addAll(item.getItems());
                list.add(temp);
            }
        }
        Collections.sort(list, new Comparator<ItemInfo>() {
            @Override
            public int compare(ItemInfo t1, ItemInfo t2) {

                if (t1.isDir() && !t2.isDir()) {
                    return -1;
                }
                if (!t1.isDir() && t2.isDir()) {
                    return 1;
                }
                return t1.getName().compareToIgnoreCase(t2.getName());
            }
        });
        return list;
    }

    private String generateKey(ItemInfo item) {
        return String.format("%s_%s", item.isDir(), item.getName().toLowerCase());
    }
}
